<template>
  <a-spin :loading="loading" class="cantainer">
    <div class="left">
      <div class="left-top">
        <a-space>
          <WorkSerialChoice choiceType="checkbox" @choice="addOrEditWorkSerial">
            <a-button type="primary">添加工序</a-button>
          </WorkSerialChoice>
          <WorkSerialGroupChoice
            choiceType="checkbox"
            @choice="addOrEditWorkSerialGroup"
          >
            <a-button type="primary">添加工序组</a-button>
          </WorkSerialGroupChoice>
        </a-space>
      </div>
      <a-empty v-if="groupData.length === 0" />
      <Draggable
        :list="groupData"
        group="groupData"
        itemKey="uuid"
        class="list"
      >
        <template #item="{ element }">
          <div
            class="item"
            @click="element.uuid === choiceUuid ? null : choiceItem(element)"
          >
            <div
              class="item-title"
              :style="{
                color:
                  choiceUuid === element.uuid ? 'rgb(var(--arcoblue-6))' : '',
              }"
            >
              <div> <icon-more-vertical :size="18" /></div>
              <div>{{ element.name }}</div>
            </div>
            <div>
              <a-link>
                <WorkSerialChoice
                  v-if="element.type === 1"
                  @choice="addOrEditWorkSerial($event, element.uuid)"
                >
                  <icon-edit :size="24" />
                </WorkSerialChoice>
                <WorkSerialGroupChoice
                  v-if="element.type === 2"
                  @choice="addOrEditWorkSerialGroup($event, element.uuid)"
                >
                  <icon-edit :size="24" />
                </WorkSerialGroupChoice>
              </a-link>

              <!-- <a-popconfirm
                @ok="deleteItem(element, rowIndex)"
                content="确定删除吗"
                type="error"
              >
                <a-link status="danger"> <icon-delete :size="24" /> </a-link>
              </a-popconfirm> -->
            </div>
          </div>
        </template>
      </Draggable>
    </div>
    <div class="leftBox">
      <div class="overview">
        <div class="overview-title">总览图</div>
        <Draggable :list="groupData" group="groupData" itemKey="uuid">
          <template #item="groupDataItem">
            <div @click="choiceItem(groupDataItem.element)">
              <div class="perpendicularArrow" v-if="groupDataItem.index" />
              <div class="groupData">
                <div
                  class="borBox bg1"
                  :class="
                    choiceUuid === groupDataItem.element.uuid ? 'choice' : ''
                  "
                >
                  {{ groupDataItem.element.name }}

                  <!-- <a-popconfirm
                    @ok="
                      () => {
                        groupData.splice(groupDataItem.index, 1);
                      }
                    "
                    content="确定删除吗"
                    type="error"
                  >
                    <div class="del">
                      <icon-minus-circle :size="20" />
                    </div>
                  </a-popconfirm> -->
                  <div
                    class="add"
                    v-if="groupDataItem.element.type === 2"
                    @click="
                      () => {
                        addWorkSerialIndex = 0;
                        refAddWorkSerialChoice.visible = true;
                      }
                    "
                  >
                    <icon-plus-circle-fill :size="20" />
                  </div>
                </div>
                <div
                  class="horizontalArrow"
                  v-if="
                    groupDataItem.element.groupSet.length &&
                    groupDataItem.element.type === 2
                  "
                />
                <Draggable
                  v-if="groupDataItem.element.type === 2"
                  :list="groupDataItem.element.groupSet"
                  :group="'groupSet' + groupDataItem.index"
                  itemKey="id"
                  class="groupDataBox"
                >
                  <template #item="groupSetItem">
                    <div
                      class="groupSet"
                      @click.stop="
                        () => {
                          choiceUuid = groupDataItem.element.uuid;
                          choiceGroupSetUuid = groupSetItem.element.uuid;
                        }
                      "
                    >
                      <div class="horizontalArrow" />
                      <div
                        class="borBox"
                        :class="
                          choiceGroupSetUuid === groupSetItem.element.uuid
                            ? 'choice'
                            : ''
                        "
                      >
                        {{ groupSetItem.element.processName }}
                        <a-popconfirm
                          @ok="
                            async () => {
                              if (groupSetItem.element.id)
                                await DelProductProcessRoute({
                                  groupId: groupSetItem.element.id,
                                });
                              groupData[groupDataItem.index].groupSet.splice(
                                groupSetItem.index,
                                1
                              );
                            }
                          "
                          content="确定删除吗"
                          type="error"
                        >
                          <div class="del">
                            <icon-minus-circle :size="20" />
                          </div>
                        </a-popconfirm>
                        <div
                          class="add"
                          v-if="groupDataItem.element.type === 2"
                          @click="
                            () => {
                              addWorkSerialIndex = groupSetItem.index + 1;
                              refAddWorkSerialChoice.visible = true;
                            }
                          "
                        >
                          <icon-plus-circle-fill :size="20" />
                        </div>
                      </div>
                      <div
                        class="horizontalArrow"
                        v-if="
                          groupDataItem.element.groupSet.length !==
                          groupSetItem.index + 1
                        "
                      />
                    </div>
                  </template>
                </Draggable>
              </div>
            </div>
          </template>
        </Draggable>
        <WorkSerialChoice
          ref="refAddWorkSerialChoice"
          @choice="addWorkSerialChoice"
        >
          <div />
        </WorkSerialChoice>
      </div>
      <a-form
        :model="groupData[choiceIndex]"
        v-if="choiceIndex !== -1 && groupData[choiceIndex].type === 2"
        ref="refForm"
        auto-label-width
        class="form"
      >
        <a-row :gutter="15">
          <a-col :span="24">
            <div class="title"> 工序组信息设置 </div>
          </a-col>
          <a-col :span="6">
            <a-form-item
              label="工序组名称"
              field="name"
              :rules="getRules('工序组名称')"
            >
              <a-input
                v-model="groupData[choiceIndex].name"
                placeholder="请输入工序组名称"
              />
            </a-form-item>
          </a-col>

          <a-col :span="6">
            <a-form-item
              label="生产方式"
              field="productionMethod"
              :rules="getRules('生产方式')"
            >
              <a-select
                v-model="groupData[choiceIndex].productionMethod"
                placeholder="请选择"
              >
                <a-option
                  v-for="item in ['自制', '委外']"
                  :key="item"
                  :value="item"
                >
                  {{ item }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :span="6">
            <a-form-item label="产出物料" field="name">
              <!-- <a-input
                v-model="groupData[choiceIndex].name"
                placeholder="请输入工序组名称"
              /> -->
              <ProductChoice
                v-model:value="groupData[choiceIndex].managementId"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <a-form
        v-if="choiceIndex !== -1 && choiceGroupSetIndex !== -1"
        :model="groupData[choiceIndex].groupSet[choiceGroupSetIndex]"
        ref="refChoiceData"
        auto-label-width
        class="form"
      >
        <a-row :gutter="15">
          <a-col :span="24">
            <div class="title"> 工序信息设置 </div>
          </a-col>
          <a-col :span="8">
            <a-form-item label="工序引用">
              <WorkSerialChoice @choice="workSerialChoice">
                <a-button type="primary">引用预设工序</a-button>
              </WorkSerialChoice>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="工序名称"
              field="processName"
              :rules="getRules('工序名称')"
            >
              <a-input
                v-model="
                  groupData[choiceIndex].groupSet[choiceGroupSetIndex]
                    .processName
                "
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="工作方式"
              field="operateType"
              :rules="getRules('工作方式')"
            >
              <a-select
                v-model="
                  groupData[choiceIndex].groupSet[choiceGroupSetIndex]
                    .operateType
                "
                placeholder="请选择"
              >
                <a-option
                  v-for="item in ['生产', '检验', '维修']"
                  :key="item"
                  :value="item"
                >
                  {{ item }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="工序类别"
              field="processType"
              :rules="getRules('工序类别')"
            >
              <DictionaryChoice
                v-model:value="
                  groupData[choiceIndex].groupSet[choiceGroupSetIndex]
                    .processType
                "
                code="工序类别"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="生产方式"
              field="productionMethod"
              :rules="getRules('生产方式')"
            >
              <a-select
                v-model="
                  groupData[choiceIndex].groupSet[choiceGroupSetIndex]
                    .productionMethod
                "
                placeholder="请选择"
              >
                <a-option
                  v-for="item in ['自制', '委外']"
                  :key="item"
                  :value="item"
                >
                  {{ item }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="是否报工"
              field="isReportingWork"
              :rules="getRules('是否报工')"
            >
              <a-select
                v-model="
                  groupData[choiceIndex].groupSet[choiceGroupSetIndex]
                    .isReportingWork
                "
                placeholder="请选择"
              >
                <a-option :value="1">是 </a-option>
                <a-option :value="2">否 </a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>

      <TabsTable
        v-show="choiceIndex !== -1 && choiceGroupSetIndex !== -1"
        :setId="
          groupData[choiceIndex] &&
          groupData[choiceIndex].groupSet[choiceGroupSetIndex]
            ? groupData[choiceIndex].groupSet[choiceGroupSetIndex].id
            : 0
        "
      />
    </div>
  </a-spin>
</template>

<script setup lang="ts">
  import Draggable from 'vuedraggable';
  import { ref, computed } from 'vue';
  import { TGroupData, TWorkSerialGroup } from '@/api/FactoryModeling/type';
  import { DelProductProcessRoute } from '@/api/FactoryModeling';
  import uniqueid from 'lodash.uniqueid';
  import WorkSerialChoice from '@/views/client-side/FactoryModeling/components/WorkSerialChoice.vue';
  import WorkSerialGroupChoice from '@/views/client-side/FactoryModeling/components/WorkSerialGroupChoice.vue';
  import TabsTable from './TabsTable.vue';

  let loading = ref();
  let choiceUuid = ref('');
  let choiceGroupSetUuid = ref('');
  let groupData = ref<TGroupData[]>([]);

  let choiceIndex = computed(() =>
    groupData.value.findIndex(({ uuid }) => uuid === choiceUuid.value)
  );
  let choiceGroupSetIndex = computed(() => {
    if (choiceIndex.value === -1) return -1;
    return groupData.value[choiceIndex.value].groupSet?.findIndex(
      ({ uuid }) => uuid === choiceGroupSetUuid.value
    );
  });

  let refAddWorkSerialChoice = ref();
  let addWorkSerialIndex = ref(0);
  let addWorkSerialChoice = ([data]: TWorkSerialGroup[]) => {
    groupData.value[choiceIndex.value].groupSet.splice(
      addWorkSerialIndex.value,
      0,
      { ...data, id: 0, uuid: uniqueid() }
    );
  };

  let choiceItem = async (choiceData?: TGroupData) => {
    choiceUuid.value = choiceData?.uuid;
    choiceGroupSetUuid.value = choiceData?.groupSet[0].uuid || '';
  };

  let deleteItem = (item: TGroupData, index: number) => {
    groupData.value.splice(index, 1);
    if (choiceUuid.value === item.uuid) {
      choiceItem();
    }
  };

  let addOrEditWorkSerial = (list: TWorkSerialGroup[], uuid?: any) => {
    let addDataList = list.map((data) => {
      return {
        name: data.processName,
        processGroupId: data.id,
        productionMethod: data.productionMethod,
        type: data.type,
        processType: data.processType,
        groupSet: [
          {
            sort: 1,
            processName: data.processName,
            productionMethod: data.productionMethod,
            processType: data.processType,
            isReportingWork: data.isReportingWork,
            operateType: data.operateType,
            uuid: uniqueid(),
          },
        ],
        uuid: uuid || uniqueid(),
      };
    });
    if (uuid) {
      Object.assign(
        groupData.value[
          groupData.value.findIndex((item) => item.uuid === uuid)
        ],
        addDataList[0]
      );
    } else {
      addDataList.forEach((item) => groupData.value.push(item));
    }
  };
  let addOrEditWorkSerialGroup = async (
    list: TWorkSerialGroup[],
    uuid?: any
  ) => {
    loading.value = true;
    try {
      // let res: TWorkSerialGroup = await GetWorkSerialGroup({ id: data.id });
      let addDataList = list.map((data) => {
        return {
          name: data.processName,
          processGroupId: data.id,
          productionMethod: data.productionMethod,
          type: data.type,
          processType: data.processType,
          uuid: uuid || uniqueid(),
          groupSet:
            data.set?.map(({ sort, processGroupData, processGroupId }) => {
              return {
                sort,
                processGroupId,
                processName: processGroupData?.processName,
                operateType: processGroupData?.operateType,
                type: processGroupData?.type,
                productionMethod: processGroupData?.productionMethod,
                processType: processGroupData?.processType,
                isReportingWork: processGroupData?.isReportingWork,
                uuid: uniqueid(),
              };
            }) || [],
        };
      });
      if (uuid) {
        Object.assign(
          groupData.value[
            groupData.value.findIndex((item) => item.uuid === uuid)
          ],
          addDataList[0]
        );
      } else {
        addDataList.forEach((item) => {
          groupData.value.push(item);
        });
      }
    } catch (err) {
      //
    }
    loading.value = false;
  };

  let setGroupData = (list?: TGroupData[], notId?: boolean) => {
    groupData.value =
      list
        ?.map((item) => {
          return {
            ...item,
            uuid: uniqueid(),
            id: notId ? undefined : item.id,
            groupSet:
              item.groupSet
                ?.map((item) => {
                  return {
                    ...item,
                    uuid: uniqueid(),
                    id: notId ? undefined : item.id,
                  };
                })
                .sort((a, b) => (a?.sort || 0) - (b?.sort || 0)) || [],
          };
        })
        .sort((a, b) => (a?.sort || 0) - (b?.sort || 0)) || [];
  };
  let getGroupData = async () => {
    return Promise.resolve(
      groupData.value.map((item, index) => {
        return {
          ...item,
          groupSet: item.groupSet?.map((item, index) => {
            return {
              ...item,
              sort: index,
            };
          }),
          sort: index + 1,
        };
      })
    );
  };
  defineExpose({ setGroupData, getGroupData });

  let getRules = (name?: string) => {
    return [{ required: true, message: (name || '') + '不能为空' }];
  };

  let workSerialChoice = ([data]: TWorkSerialGroup[]) => {
    Object.assign(
      groupData.value[choiceIndex.value].groupSet[choiceGroupSetIndex.value],
      {
        ...data,
        uuid: choiceGroupSetUuid.value,
        id: groupData.value[choiceIndex.value].groupSet[
          choiceGroupSetIndex.value
        ].id,
      }
    );
    if (groupData.value[choiceIndex.value].type === 1) {
      Object.assign(groupData.value[choiceIndex.value], {
        name: data.processName,
        uuid: choiceUuid.value,
        operateType: data.operateType,
        processGroupId: data.id,
        processType: data.processType,
        productionMethod: data.productionMethod,
        id: 0,
      });
    }
  };
</script>

<style scoped lang="less">
  .perpendicularArrow {
    border-left: 1px rgb(var(--arcoblue-6)) solid;
    height: 30px;
    margin-left: 70px;
  }
  .overview {
    width: 100%;
    padding: 30px;
    display: flex;
    justify-content: center;
    position: relative;
    min-height: 200px;
    background: -webkit-linear-gradient(
        top,
        transparent 15px,
        var(--color-neutral-2) 0
      ),
      -webkit-linear-gradient(left, transparent 15px, var(--color-neutral-2) 0);
    background-size: 16px 16px;
    overflow-y: hidden;
    &-title {
      position: absolute;
      left: 20px;
      top: 20px;
      background: #fff;
      width: 80px;
      height: 35px;
      border-radius: 25px;
      border: 1px solid var(--color-neutral-4);
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .groupData {
    display: flex;
    align-items: center;

    .horizontalArrow {
      border-top: 1px rgb(var(--arcoblue-6)) solid;
      width: 30px;
    }
    .choice {
      box-shadow: 0px 0px 10px rgb(var(--arcoblue-6));
      color: rgb(var(--arcoblue-6));
    }

    .borBox {
      position: relative;
      border: 1px rgb(var(--arcoblue-6)) solid;
      cursor: pointer;
      border-radius: 5px;
      width: 139px;
      height: 70px;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #fff;
      .del {
        position: absolute;
        right: -10px;
        background: #fff;
        top: -10px;
        color: rgb(var(--red-6));
        border-radius: 15px;
      }
      .add {
        position: absolute;
        right: -10px;
        background: #fff;
        color: rgb(var(--arcoblue-6));
        border-radius: 15px;
      }
    }

    .borBox:hover {
      box-shadow: 0px 0px 5px rgb(var(--arcoblue-6));
    }
    .bg1 {
      background-color: rgb(var(--arcoblue-1));
    }

    .groupDataBox {
      display: flex;
      .groupSet {
        display: flex;
        align-items: center;
      }
    }
  }
  .cantainer {
    border-top: 1px solid var(--color-neutral-4);
    display: flex;
    height: 700px;
    border-bottom: 1px solid var(--color-neutral-4);
    .leftBox {
      flex: 1;
      overflow-x: hidden;
      height: 700px;

      .title {
        font-size: 20px;
        margin-bottom: 20px;
      }
      .form {
        padding: 20px 20px 0px 20px;
      }
    }
    .left {
      height: 100%;
      width: 20vw;
      border-right: 1px solid var(--color-neutral-4);
      &-top {
        display: flex;
        justify-content: center;
        border-bottom: 1px solid var(--color-neutral-4);
        padding: 10px 0;
      }

      .list {
        overflow-x: hidden;
        height: calc(100% - 60px);
      }
      .item {
        border-bottom: 1px solid var(--color-neutral-4);
        height: 40px;
        display: flex;
        align-items: center;
        padding: 0 10px;
        justify-content: space-between;
        cursor: pointer;
        &-title {
          display: flex;
          align-items: center;
        }
      }
    }
  }
</style>
